package frame.usermeau;

import frame.model.SnowflakeIdWorker;
import frame.usermeau.service.serviceimpl.FundServiceFrame;
import frame.usermeau.service.IdCardFrame;
import frame.usermeau.service.serviceimpl.InsuranceServiceFrame;
import frame.usermeau.service.serviceimpl.ProductServiceFrame;
import tech.tablesaw.api.DoubleColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserHomepageFrame extends JFrame {

    private String name = "";
    private String idCard = "37342583336625766400";
    private String phoneNumber = "";
    private String email = "";

    Connection conn;

    public void init() {
        try {
            Class.forName("org.opengauss.Driver");
            conn = DriverManager.getConnection("jdbc:opengauss://121.36.41.207:26000/finance", "geqiyu", "Tlyz0729");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        try {
            // 设置demo为搜索路径
            PreparedStatement firstStep = conn.prepareStatement("SET SEARCH_PATH TO finance,public");
            firstStep.execute();
            firstStep.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public UserHomepageFrame() {
        this.setTitle("用户主界面");
        //操作
        this.getUserMessage();
        this.setContentPane(showUserMessage());
        //设置窗口
        this.setBounds(580,280,700,700);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public UserHomepageFrame(String name,String idCard,String phoneNumber,String email) {
        this.setTitle("用户主界面");

        this.name = name;
        this.idCard = idCard;
        this.phoneNumber = phoneNumber;
        this.email = email;

        //操作
        this.getUserMessage();
        this.setContentPane(showUserMessage());
        //设置窗口
        this.setBounds(580,280,700,700);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);

    }


    /**
     * UI,显示用户的基础信息和可执行操作，无需修改
     * @return
     */
    private JPanel showUserMessage() {
        JPanel jPanel = new JPanel(null);

        //显示个人信息
        int x = 30, y = 20;
        int xc = 150, yc = 40;
        int width = 150, height = 20;
        String[][] label = {{"姓名:", "身份证号:"},{"电话:", "邮箱:"}};
        String[][] message = {{name, idCard}, {phoneNumber, email}};
        JLabel jl;
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                jl = new JLabel(label[i][j]);
                jl.setSize(width, height);
                jl.setLocation(x+xc*j, y+yc*i);
                jPanel.add(jl);
                jl = new JLabel(message[i][j]);
                jl.setSize(width, height);
                jl.setLocation(x+xc*j+60, y+yc*i);
                jPanel.add(jl);
            }
        }

        //业务按钮
        JButton jb;
        JComboBox service = new JComboBox();
        service.setSize(100,20);
        service.setLocation(400,20);

        service.addItem("业务办理");
        service.addItem("理财产品");
        service.addItem("保险");
        service.addItem("基金");
        service.addItem("银行卡");

        service.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String mess = service.getSelectedItem().toString();
                if("理财产品".equals(mess)) {
                    new ProductServiceFrame(idCard).init("理财产品");
                }else if("保险".equals(mess)) {
                    new InsuranceServiceFrame(idCard).init("保险");
                }else if("基金".equals(mess)){
                    new FundServiceFrame(idCard).init("基金");
                }else if("银行卡".equals(mess)){
                    new IdCardFrame(idCard);
                }
            }
        });
        jPanel.add(service);

        //查询按钮
        JComboBox query = new JComboBox();
        query.setSize(120,20);
        query.setLocation(520,20);

        query.addItem("查询已有业务");
        query.addItem("理财产品");
        query.addItem("保险");
        query.addItem("基金");
        query.addItem("银行卡");
        jPanel.add(query);

        //结果框
        JTextArea jTextArea = new JTextArea();
        jTextArea.setSize(600, 500);
        jTextArea.setLocation(40,140);
        jPanel.add(jTextArea);

        //设置监听事件
        query.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String mess = query.getSelectedItem().toString();
                Table message = getMessage(mess);
                jTextArea.setFont(new Font("Default",Font.PLAIN,18));
                jTextArea.setText("");
                jTextArea.setText(message.print());
            }
        });
        return jPanel;
    }


    /**
     * 获取用户基本信息，也就是给属性赋值：姓名、身份证、电话、邮箱
     */
    private void getUserMessage() {
        /*
        -------------------------------------------------------------------------------------------------------------------------------
            业务逻辑
//        name = ;
//        idCard = ;
//        phoneNumber = ;
//        email = ;
        -------------------------------------------------------------------------------------------------------------------------------
         */
    }


    /**
     * 获取查询的结果
     * @param query 查询业务
     * @return  返回字符串数组结果
     */
    private Table getMessage(String query) {
        Table table = null;
        if ("基金".equals(query)) {
            List<String> fundIdList = new ArrayList<>();
            List<String> fundNameList = new ArrayList<>();
            List<String> fundMountList = new ArrayList<>();
            List<String> fundIncomeList = new ArrayList<>();
            init();
            try {
                PreparedStatement preparedStatement = conn.prepareStatement("select  fund.fu_id, fund.fu_name, assert.fua_amount, assert.fua_income " +
                        "    from t_fund as fund,t_fundassets as assert" +
                        "    where assert.fua_user_id = ?" +
                        "    and fund.fu_id = assert.fua_fund_id;");
                preparedStatement.setString(1,idCard);
                ResultSet resultSet = preparedStatement.executeQuery();
                while(resultSet.next()) {
                    String fundId = resultSet.getString(1);
                    String fundName = resultSet.getString(2);
                    String amountMoney = resultSet.getString(3);
                    String income = resultSet.getString(4);
                    fundIdList.add(fundId);
                    fundNameList.add(fundName);
                    fundMountList.add(amountMoney);
                    fundIncomeList.add(income);
                }
                table = Table.create("我的基金").addColumns(
                        StringColumn.create("基金ID",fundIdList),
                        StringColumn.create("基金名称",fundNameList),
                        StringColumn.create("基金总额",fundMountList),
                        StringColumn.create("基金收益",fundIncomeList)
                );
                resultSet.close();
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }else if ("保险".equals(query)) {

            List<String> insureIdList = new ArrayList<>();
            List<String> insureNameList = new ArrayList<>();
            List<String> insureMountList = new ArrayList<>();
            List<String> insureTimeList = new ArrayList<>();
            init();
            PreparedStatement preparedStatement = null;
            try {
                preparedStatement = conn.prepareStatement("select insure.in_id, insure.in_name, asserts.ina_amount, insure.in_period from t_insurance as insure, t_insassets asserts where asserts.ina_user_id = ? and insure.in_id = asserts.ina_insurance_id;");
                preparedStatement.setString(1,idCard);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    String insureId = resultSet.getString(1);
                    String insureName = resultSet.getString(2);
                    String amount = resultSet.getString(3); // 保险购买金额
                    String insurePerid = resultSet.getString(4);
                    insureIdList.add(insureId);
                    insureNameList.add(insureName);
                    insureMountList.add(amount);
                    insureTimeList.add(insurePerid);
                }
                table = Table.create("我的保险").addColumns(
                        StringColumn.create("基金ID",insureIdList),
                        StringColumn.create("保险名称",insureNameList),
                        StringColumn.create("保险总额",insureMountList),
                        StringColumn.create("保险时间",insureTimeList)
                );
                preparedStatement.close();
                conn.close();
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if ("理财产品".equals(query)) {

            List<String> productIdList = new ArrayList<>();
            List<String> productNameList = new ArrayList<>();
            List<String> productMountList = new ArrayList<>();
            List<String> productIncomeList = new ArrayList<>();
            init();
            PreparedStatement preparedStatement = null;
            try {
                preparedStatement = conn.prepareStatement("select product.fp_id, product.fp_name, asserts.fpa_amount, asserts.fpa_income from t_product product, t_proassets asserts where product.fp_id=asserts.fpa_product_id and asserts.fpa_user_id = ?;");
                preparedStatement.setString(1,idCard);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    String productId = resultSet.getString(1);
                    String productName = resultSet.getString(2);
                    String amount = resultSet.getString(3);
                    String income = resultSet.getString(4);
                    productIdList.add(productId);
                    productNameList.add(productName);
                    productMountList.add(amount);
                    productIncomeList.add(income);
                }
                table = Table.create("我的理财产品").addColumns(
                        StringColumn.create("产品ID",productIdList),
                        StringColumn.create("产品名称",productNameList),
                        StringColumn.create("产品总额",productMountList),
                        StringColumn.create("产品收益",productIncomeList)
                );
                preparedStatement.close();
                conn.close();
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if("银行卡".equals(query)) {

            List<String> cardIdList = new ArrayList<>();
            List<String> cardTypeList = new ArrayList<>();
            init();
            PreparedStatement preparedStatement = null;
            try {
                preparedStatement = conn.prepareStatement("select card.c_id, card.c_type from t_card card where card.c_user_id = ?;");
                preparedStatement.setString(1,idCard);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    String userCardId = resultSet.getString(1);
                    int cardType = resultSet.getInt(2);
                    cardIdList.add(userCardId);
                    cardTypeList.add(cardType == 0 ? "储蓄卡" : "信用卡");
                }
                table = Table.create("我的银行卡").addColumns(
                        StringColumn.create("银行卡卡号",cardIdList),
                        StringColumn.create("银行卡类型",cardTypeList)
                );
                preparedStatement.close();
                conn.close();
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return table;
    }


    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        new UserHomepageFrame();
    }
}
